import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:management/app/cons.dart';
import 'package:management/model/visitor_model.dart';
import 'package:management/utils/channel.dart';
import 'package:management/utils/custom_router.dart';
import 'package:management/utils/log_utils.dart';
import 'package:management/views/visitor/checkIn/idCard_widget.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:management/views/visitor/checkIn/reason_for_the_visit.dart';

///身份证登记
class IDCardRegistration extends StatefulWidget {
  @override
  _IDCardRegistrationState createState() => _IDCardRegistrationState();
}

class _IDCardRegistrationState extends State<IDCardRegistration> {
  ///姓名编辑控制器
  late TextEditingController _nameController;

  ///证件号码编辑控制器
  late TextEditingController _IDNumberController;

  ///联系电话编辑控制器
  late TextEditingController _telephoneNumController;

  ///访客住址编辑控制器
  late TextEditingController _visitorAddressController;

  ///访客单位编辑控制器
  late TextEditingController _visitorUnitController;

  ///保存照片的路径
  String _picPath = "";

  ///访客姓名
  late String _name;

  ///访客性别
  String _sex = "男";

  ///民族
  String _nationality = "汉";

  ///出生日期
  String _dateOfBirth = '自动生成';

  ///出生日期
  // String _birthday;

  ///证件类型
  String _typeOfCertificate = '身份证';

  ///证件号码
  late String _IDNumber;

  ///电话号码
  late String _telephoneNum;

  ///访客住址
  late String _visitorAddress;

  ///访客单位
  late String _visitorUnit;

  ///下方提示
  String _prompt = "读卡器未连接";

  @override
  void initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.initState();
    _nameController = TextEditingController();
    _IDNumberController = TextEditingController();
    _telephoneNumController = TextEditingController();
    _visitorAddressController = TextEditingController();
    _visitorUnitController = TextEditingController();
    BluetoothChannel.bluetoothChannel!.setMessageHandler((message) {
      if (message is Map) {
        if (message["method"] == "receiveIDCardMsg") {
          if (message['retCode'] != 1) {
            Fluttertoast.showToast(msg: "读卡失败!");
            return Future.error("error");
          }
          setState(() {
            _nameController.text = message["partyName"];
            _sex = message["gender"];
            _nationality = message["nation"];
            if (!TextUtil.isEmpty(message['bornDay'])) {
              // _birthday = DateUtil.formatDateStr(message["bornDay"],
              //     format: 'yyyy-MM-dd');
              _dateOfBirth = DateUtil.formatDateStr(message["bornDay"],
                  format: 'yyyy-MM-dd');
            }
            _typeOfCertificate = "身份证";
            _IDNumberController.text = message["certNumber"];
            _visitorAddressController.text = message["certAddress"];
            _picPath = message["picPath"];
          });
        }

        if (message["method"] == "connectState") {
          bool connect = message["connectState"];
          connect
              ? BluetoothChannel.isConnectedDevice = true
              : BluetoothChannel.isConnectedDevice = false;
          Fluttertoast.showToast(msg: connect ? "连接成功" : "连接失败");
        }
      }
      MyLog.w("message : ${message.toString()}");
      return Future.error("null");
    });
  }

  AppBar _buildAppBar() => AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          iconSize: 35,
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          "身份证登记",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
        ),
        centerTitle: true,
        backgroundColor: Colors.blue,
        actions: [
          PopupMenuButton(
            offset: Offset(0, 20),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(0),
            ),
            icon: Image.asset('assets/images/card_reader.png',
                fit: BoxFit.cover, width: 50, height: 50),
            itemBuilder: _buildPopMenuItem,
            onSelected: (value) async {
              MyLog.d("value: $value");
              if (value == "蓝牙读卡器") {
                Navigator.of(context).pop();
                Navigator.of(context).pushNamed('/SearchBlt');
              }
            },
          ),
          Padding(
            padding: EdgeInsets.only(left: 20, right: 20, top: 5, bottom: 5),
            child: MaterialButton(
              child: Text(
                "下一步",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 25,
                    fontWeight: FontWeight.bold),
              ),
              onPressed: () {
                MyLog.d("下一步");
                // 检查获取字段值 插入表记录
                // 跳转到访问事由界面
                onNext();
              },
            ),
          ),
        ],
      );

  @Deprecated("下方提示变化未确定")
  void onClick() {
    for (int i = 0; i <= 9; i++) {
      switch (i) {
        case 0:
        case 3:
        case 6:
          Future.delayed(
              Duration(seconds: i), () => setState(() => _prompt = "读卡器连接中."));
          break;
        case 1:
        case 4:
        case 7:
          Future.delayed(
              Duration(seconds: i), () => setState(() => _prompt = "读卡器连接中.."));
          break;
        case 2:
        case 5:
        case 8:
          Future.delayed(Duration(seconds: i),
              () => setState(() => _prompt = "读卡器连接中..."));
          break;
        case 9:
          Future.delayed(
              Duration(seconds: i), () => setState(() => _prompt = "读卡器未连接"));
          break;
      }
    }
  }

  ///构建脚手架 body
  Widget _buildBody() => ListView(
        children: [
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            color: Colors.black12,
            child: Stack(
              children: [
                Positioned(
                  child: Text(
                    "访客信息",
                    style: TextStyle(
                        fontSize: 25,
                        color: Colors.black,
                        fontWeight: FontWeight.bold),
                  ),
                  top: 50,
                  left: 30,
                ), //左边文字 【访客信息】
                Positioned(
                  child: Container(
                    width: 0.9.sw,
                    height: 0.65.sh,
                    padding: EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: Colors.grey, width: 2),
                      color: Colors.white,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          width: 1680,
                          height: 250,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                width: 1230,
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Container(
                                      height: 50,
                                      // color: Colors.grey,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "访客姓名",
                                            style: TextStyle(
                                              fontSize: 25,
                                              color: Colors.blue,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          Container(
                                            // alignment: Alignment.bottomLeft,
                                            width: 1100,
                                            child: TextField(
                                              controller: _nameController,
                                              style: TextStyle(
                                                  fontSize: 20,
                                                  fontWeight: FontWeight.bold),
                                              textAlign: TextAlign.left,
                                              textAlignVertical:
                                                  TextAlignVertical.bottom,
                                              inputFormatters: [],
                                              keyboardType: TextInputType.text,
                                              decoration: InputDecoration(
                                                hintText: "请输入姓名",
                                                hintStyle:
                                                    TextStyle(fontSize: 20),
                                                border: OutlineInputBorder(),
                                              ),
                                              onChanged: (name) {
                                                // MyLog.i("访客姓名： $name");
                                              },
                                            ),
                                          ),
                                        ],
                                      ),
                                    ), // 访客姓名
                                    Container(
                                      height: 50,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "性        别",
                                            style: TextStyle(
                                                fontSize: 25.sp,
                                                color: Colors.blue,
                                                fontWeight: FontWeight.bold),
                                          ),
                                          Container(
                                            width: 1100,
                                            padding: EdgeInsets.only(left: 10),
                                            decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Colors.grey),
                                              borderRadius: BorderRadius.only(
                                                topLeft: Radius.circular(5),
                                                topRight: Radius.circular(5),
                                                bottomLeft: Radius.circular(5),
                                                bottomRight: Radius.circular(5),
                                              ),
                                            ),
                                            child: DropdownButtonHideUnderline(
                                              child: DropdownButton(
                                                value: _sex,
                                                items: [
                                                  DropdownMenuItem(
                                                    child: Text(
                                                      "男",
                                                      style: TextStyle(
                                                        fontSize: 20,
                                                        fontWeight:
                                                            FontWeight.bold,
                                                      ),
                                                    ),
                                                    value: "男",
                                                  ),
                                                  DropdownMenuItem(
                                                    child: Text(
                                                      '女',
                                                      style: TextStyle(
                                                        fontSize: 20,
                                                        fontWeight:
                                                            FontWeight.bold,
                                                      ),
                                                    ),
                                                    value: "女",
                                                  ),
                                                ],
                                                onChanged: (v) {
                                                  setState(() => _sex = v.toString());
                                                },
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ), //性别
                                    Container(
                                      height: 50,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "民        族",
                                            style: TextStyle(
                                              fontSize: 25,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          Container(
                                            width: 1100,
                                            decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Colors.grey),
                                              borderRadius: BorderRadius.only(
                                                topLeft: Radius.circular(5),
                                                topRight: Radius.circular(5),
                                                bottomRight: Radius.circular(5),
                                                bottomLeft: Radius.circular(5),
                                              ),
                                            ),
                                            padding: EdgeInsets.only(left: 10),
                                            child: DropdownButtonHideUnderline(
                                              child: DropdownButton(
                                                value: _nationality,
                                                items: _buildMinZuItem(),
                                                onChanged: (value) {
                                                  setState(() =>
                                                      _nationality = value.toString());
                                                },
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ), //民族
                                    Container(
                                      height: 50,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            "出生日期",
                                            style: TextStyle(
                                              fontSize: 25,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                          _buildBirthItem(context),
                                        ],
                                      ),
                                    ), //出生日期
                                  ],
                                ),
                              ),
                              VisitorPhoto(
                                400,
                                400,
                                filePath: _picPath,
                              ),
                              //访客相片
                            ],
                          ),
                        ),

                        Container(
                          height: 70,
                          width: 1680,
                          // color: Colors.grey,
                          // alignment: Alignment.topLeft,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                margin: EdgeInsets.only(top: 16.h),
                                // color: Colors.redAccent,
                                child: Text(
                                  "证件类型",
                                  style: TextStyle(
                                    fontSize: 25.sp,
                                    color: Colors.blue,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              Container(
                                width: 680.w,
                                padding: EdgeInsets.only(left: 10.w),
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.grey),
                                  borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(5.w),
                                    topRight: Radius.circular(5.w),
                                    bottomLeft: Radius.circular(5.w),
                                    bottomRight: Radius.circular(5.w),
                                  ),
                                ),
                                child: DropdownButtonHideUnderline(
                                  child: DropdownButton(
                                    value: _typeOfCertificate,
                                    items: _buildZhengJianItem(),
                                    onChanged: (value) {
                                      setState(
                                          () => _typeOfCertificate = value.toString());
                                    },
                                  ),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 16.h),
                                child: Text(
                                  "证件号码",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.blue,
                                    fontSize: 25.sp,
                                  ),
                                ),
                              ),
                              Container(
                                width: 710.w,
                                alignment: Alignment.bottomCenter,
                                // color: Colors.yellow,
                                child: TextField(
                                  style: TextStyle(fontSize: 20.sp),
                                  textAlign: TextAlign.left,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  controller: _IDNumberController,
                                  keyboardType: TextInputType.number,
                                  maxLength: 18,
                                  autofocus: false,
                                  decoration: InputDecoration(
                                    hintText: "请输入证件号码",
                                    hintStyle: TextStyle(fontSize: 20.sp),
                                    border: OutlineInputBorder(),
                                  ),
                                  onChanged: (value) {
                                    //xxxxxx19971027xxxx
                                    if (value.length == 18) {
                                      var substring = value.substring(
                                          6, 14); //截取出生日期 19971027
                                      var year = substring.substring(0, 4);
                                      var month = substring.substring(4, 6);
                                      var day = substring.substring(6);
                                      setState(() {
                                        _dateOfBirth = "$year-$month-$day";
                                      });
                                      MyLog.i("$year-$month-$day");
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        ), //证件类型
                        Container(
                          width: 1680.w,
                          height: 70.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                // color: Colors.grey,
                                padding: EdgeInsets.only(bottom: 20),
                                child: Text(
                                  "联系电话",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25.sp,
                                    color: Colors.blue,
                                  ),
                                ),
                              ),
                              Container(
                                width: 1550.w,
                                child: TextField(
                                  style: TextStyle(fontSize: 20.sp),
                                  textAlign: TextAlign.left,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  controller: _telephoneNumController,
                                  maxLength: 11,
                                  decoration: InputDecoration(
                                    border: OutlineInputBorder(),
                                    hintText: "请输入电话号码",
                                    hintStyle: TextStyle(fontSize: 20.sp),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          width: 1680.w,
                          height: 50.h,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "访客住址",
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 25.sp),
                              ),
                              Container(
                                width: 1550.w,
                                child: TextField(
                                  style: TextStyle(fontSize: 20.sp),
                                  textAlign: TextAlign.left,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  controller: _visitorAddressController,
                                  decoration: InputDecoration(
                                      hintText: "请输入访客住址",
                                      hintStyle: TextStyle(fontSize: 20.sp),
                                      border: OutlineInputBorder()),
                                ),
                              )
                            ],
                          ),
                        ), //访客住址
                        Container(
                          height: 50.w,
                          width: 1680.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                "访客单位",
                                style: TextStyle(
                                  fontSize: 25.w,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              Container(
                                width: 1550.w,
                                child: TextField(
                                  style: TextStyle(fontSize: 20.sp),
                                  textAlign: TextAlign.left,
                                  textAlignVertical: TextAlignVertical.bottom,
                                  controller: _visitorUnitController,
                                  decoration: InputDecoration(
                                    hintText: "请输入访客单位",
                                    hintStyle: TextStyle(fontSize: 20.sp),
                                    border: OutlineInputBorder(),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ), // 访客单位
                      ],
                    ),
                  ),
                  top: 15.h,
                  right: 15.w,
                ), // 右边内容
                Positioned(
                  bottom: 200.h,
                  right: 500.w,
                  left: 500.w,
                  child: Container(
                    child: MaterialButton(
                      height: 60,
                      color: Colors.blue,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(50)),
                      ),
                      onPressed: () {
                        intervalClick();
                      },
                      child: Text(
                        _prompt,
                        style: TextStyle(color: Colors.white, fontSize: 35),
                      ),
                    ),
                  ),
                ),
                Positioned(
                  bottom: 180,
                  // right: 300,
                  left: 858,
                  child: BluetoothChannel.isConnectedDevice
                      ? Text("请先连接读卡器再点击读卡按钮")
                      : Text(""),
                ) //下方提示
              ],
            ),
          )
        ],
      );

  //构建民族的选项
  List<DropdownMenuItem<String>> _buildMinZuItem() => Cons.nationality
      .map((e) => DropdownMenuItem(
            child: Text(
              e,
              style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
            ),
            value: e,
          ))
      .toList();

  //构建出生日期
  Widget _buildBirthItem(BuildContext context) => Container(
        width: 1100.w,
        child: Text(
          _dateOfBirth,
          style: TextStyle(
            fontSize: 20.sp,
          ),
        ),
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 10.w),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(5.w),
            topRight: Radius.circular(5.w),
            bottomRight: Radius.circular(5.w),
            bottomLeft: Radius.circular(5.w),
          ),
        ),
      );

  //构建证件类型
  List<DropdownMenuItem<String>> _buildZhengJianItem() => Cons.zhengJianLeiXing
      .map((e) => DropdownMenuItem(
            value: e,
            child: Text(
              e,
              style: TextStyle(fontSize: 20.sp, fontWeight: FontWeight.bold),
            ),
          ))
      .toList();

  //构建读卡器弹出框
  List<PopupMenuEntry> _buildPopMenuItem(BuildContext context) {
    return <PopupMenuEntry<String>>[
      PopupMenuItem(value: "蓝牙读卡器", child: Text("蓝牙读卡器")),
    ];
  }

  @override
  Widget build(BuildContext context) {
    if (BluetoothChannel.isConnectedDevice &&
        BluetoothChannel.isOpenBluetooth) {
      _prompt = "读卡";
    }
    return Scaffold(
      appBar: _buildAppBar(),
      body: _buildBody(),
    );
  }

  //下一步
  void onNext() {
    _name = _nameController.text;
    //_sex
    //_nationality
    //_dateOfBirth
    //_typeOfCertificate
    _IDNumber = _IDNumberController.text;
    _telephoneNum = _telephoneNumController.text;
    _visitorAddress = _visitorAddressController.text;
    _visitorUnit = _visitorUnitController.text;
    if (TextUtil.isEmpty(_name)) {
      Fluttertoast.showToast(msg: "请输入访客姓名");
      return;
    }
    if (TextUtil.isEmpty(_IDNumber)) {
      Fluttertoast.showToast(msg: "请输入证件号码");
      return;
    } else if (_typeOfCertificate == "身份证" && _IDNumber.length != 18) {
      MyLog.i("_typeOfCertificate: $_typeOfCertificate");
      Fluttertoast.showToast(msg: "请输入正确的身份证件号码");
      return;
    }

    if (TextUtil.isEmpty(_telephoneNum)) {
      Fluttertoast.showToast(msg: "请输入联系电话");
      return;
    } else if (_telephoneNum.length != 11) {
      Fluttertoast.showToast(msg: "请输入正确的电话号码");
      return;
    }
    MyLog.i("""访客姓名：$_name
性别：$_sex
民族：$_nationality
出生日期：$_dateOfBirth
证件类型：$_typeOfCertificate
证件号码：$_IDNumber
联系电话: $_telephoneNum
访客住址：$_visitorAddress
访客单位：$_visitorUnit
    """);
    Visitor visitor = Visitor(
      _name,
      _sex,
      _typeOfCertificate,
      _IDNumber,
      nationality: _nationality,
      dateOfBirth: _dateOfBirth,
      visitorAddress: _visitorAddress,
      telephoneNum: _telephoneNum,
      visitorUnit: _visitorUnit,
    );

    // Navigator.of(context).pushNamed('/visitReason', arguments: visitor);
    Navigator.push(
        context,
        SlideRoute(VisitReason(
          visitor: visitor,
        )));
  }

  ///接收蓝牙读卡器数据
  void receiveMessage() async {
    await BluetoothChannel.bluetoothChannel!.send("receiveMessage");
  }

  @override
  void dispose() {
    super.dispose();
  }

  var lastClickTime = DateTime.now();

  //防止多次点击
  void intervalClick() {
    if (DateTime.now().difference(lastClickTime) < Duration(seconds: 2)) {
      // print("不能多次点击");
      return;
    } else {
      lastClickTime = DateTime.now();
    }
    if (BluetoothChannel.isConnectedDevice) {
      try {
        receiveMessage();
      } on Exception {} catch (e) {
        print(e);
      }
    }
  }
}
